//------------------------------------------------------------------------------
#include <QtGui>
#include <QMessageBox>
#include <QDate>
#include <QFileDialog>
#include <QFile>
#include <QFileInfo>
#include <QSqlRecord>
#include "CFindFrm.h"
#include "CComboResultFrm.h"
#include "CSocieteFrm.h"
#include "version.h"
#include "CMySQL.h"
#include "CHelp.h"
#include "CMimeType.h"
//------------------------------------------------------------------------------
CSocieteFrm::CSocieteFrm(QString name, QString lastId, CMainFrm *parent) : CMyMainWindow(name, parent) {
	setActionCur(CGlobal::acConstruct);
	
	setupUi(this);
	
	setObjectName(name);
	setStatusBar(NULL);
	
	masterTable="societe";
	primaryKey="id";
	mainFrm=parent;
	
	makeActions();
	makeMenu();
	
	loadSchema();
	
	if(CMySQL::getInstance()->getNbEnregistrement(masterTable) == 0) {
		setActionCur(CGlobal::acTableVide);
	}else {
		if(!chargeDonnees(lastId, CGlobal::seNone)) chargeDonnees("", CGlobal::sePremier);
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::setActionCur(CGlobal::EAction action) {
	actionCur=action;
	
	switch(actionCur) {
		case CGlobal::acNone:
			actPremiereFiche->setEnabled(true);
			actFichePrecedente->setEnabled(true);
			actFicheSuivante->setEnabled(true);
			actDerniereFiche->setEnabled(true);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(true);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(true);
			
			id->setEnabled(false);
			pictureChange=false;
			break;
		case CGlobal::acTableVide:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(true);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(false);
			actAnnuler->setEnabled(false);
			
			actRechercheUneFiche->setEnabled(false);
			
			clearChamps();
			enableChamps(false);
			creation->setValue("");
			break;
		case CGlobal::acAjout:
			clearChamps();
			initChamps();
			enableChamps(true);
			id->setValue(CMySQL::getInstance()->getNextCode("societe", "id"));
			id->setEnabled(false);
			nom->setFocus();
			loadImage(QImage::fromData(0, 0));
			
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(false);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(true);
			actAnnuler->setEnabled(true);
			
			actRechercheUneFiche->setEnabled(false);
			break;
		case CGlobal::acModif:
			actPremiereFiche->setEnabled(false);
			actFichePrecedente->setEnabled(false);
			actFicheSuivante->setEnabled(false);
			actDerniereFiche->setEnabled(false);
			
			actAjouter->setEnabled(false);
			actSupprimer->setEnabled(false);
			
			actValider->setEnabled(true);
			actAnnuler->setEnabled(true);
			
			actRechercheUneFiche->setEnabled(false);
		default:
			break;
	}
}
//------------------------------------------------------------------------------
CGlobal::EAction CSocieteFrm::getActionCur(void) {
	return actionCur;
}
//------------------------------------------------------------------------------
void CSocieteFrm::closeEvent(QCloseEvent * event) {
	if(getActionCur() != CGlobal::acNone && getActionCur() != CGlobal::acTableVide) {
		QMessageBox msgBox(	QMessageBox::Warning, tr("Attention"), 
							tr("Veuillez annuler ou valider avant de sortir"), QMessageBox::Ok);
		msgBox.exec();	
		
		event->ignore();
	}else {
		emit quit(objectName(), curCode);
		event->accept();
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::makeRequete(QString &requete, QString &alias) {
	requete="SELECT id, nom, adresse1, adresse2, adresse3, codePostal, ville, pays, telephone, ";
	requete+="fax, mail, web, siren, naf, tva, status, creation, logo, formulePolitesse, referencesBancaires ";
	requete+="FROM "+masterTable;
}
//------------------------------------------------------------------------------
void CSocieteFrm::showFormulaire(QSqlQuery *query, CGlobal::EAction& action) {
	QSqlRecord rec=query->record();
	
	curCode=rec.value("id").toString();
	id->setValue(curCode);
	nom->setValue(rec.value("nom"));
	adresse1->setValue(rec.value("adresse1"));
	adresse2->setValue(rec.value("adresse2"));
	adresse3->setValue(rec.value("adresse3"));
	codePostal->setValue(rec.value("codePostal"));
	ville->setValue(rec.value("ville"));
	pays->setValue(rec.value("pays"));
	telephone->setValue(rec.value("telephone"));
	fax->setValue(rec.value("fax"));
	mail->setValue(rec.value("mail"));
	web->setValue(rec.value("web"));
	siren->setValue(rec.value("siren"));
	naf->setValue(rec.value("naf"));
	tva->setValue(rec.value("tva"));
	status->setValue(rec.value("status"));
	creation->setValue(rec.value("creation"));
	formulePolitesse->setValue(rec.value("formulePolitesse"));
	referencesBancaires->setValue(rec.value("referencesBancaires"));

	loadImage(QImage::fromData(rec.value("logo").toByteArray()));
}
//------------------------------------------------------------------------------
void CSocieteFrm::loadImage(QImage image)
{
	QPicture picture;
	QPainter painter;
	double width=image.width();
	double height=image.height();
	double lWidth=logo->width()-2;
	double lHeight=logo->height()-2;
	double ratio;
	
	if(!image.isNull()) {
		if(width > height) {
			ratio=width/lWidth;
			width=lWidth;
			height/=ratio;
		}else {
			ratio=height/lHeight;
			height=lHeight;
			width/=ratio;
		}
		
		painter.begin(&picture);
		painter.drawImage(QRect(1, 1, width, height), image);
		logo->setText("");
		logo->setPicture(picture);
	}else {
		logo->setText(tr("<Pas d'image>"));
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::makeActions(void)
{
	actAddImage=new QAction(QIcon(":coMexpert/images/db_add.png"), tr("&Ajouter une image"), this);
	actAddImage->setIconVisibleInMenu(true);
	connect(actAddImage, SIGNAL(triggered()), this, SLOT(actAddImage_triggered()));
	
	actDropImage=new QAction(QIcon(":coMexpert/images/db_remove.png"), tr("&Supprimer l'image"), this);
	actDropImage->setIconVisibleInMenu(true);
	connect(actDropImage, SIGNAL(triggered()), this, SLOT(actDropImage_triggered()));
}
//------------------------------------------------------------------------------
void CSocieteFrm::makeMenu(void)
{
	popupMenu=new QMenu(logo);
	
	popupMenu->addAction(actAddImage);
	popupMenu->addAction(actDropImage);
}
//------------------------------------------------------------------------------
void CSocieteFrm::on_actAjouter_triggered(void)
{
	setActionCur(CGlobal::acAjout);
	
	creation->setValue(CMySQL::getInstance()->getCurrentDate().toString("dd/MM/yyyy"));
}
//------------------------------------------------------------------------------
void CSocieteFrm::on_actValider_triggered(void)
{
	QString requete;
	QString condition;
	
	calculChamps(getActionCur());
	
	if(!validChamps()) return;
	if(!validLiaison()) return;
	
	switch(getActionCur())
	{
		case CGlobal::acAjout:
		case CGlobal::acAjoutFromOther:
			requete="INSERT INTO "+masterTable+" SET ";
			requete+="creation=CURDATE(), createur=\""+CMySQL::getInstance()->getUser()+"\", ";
			condition="";
			break;
		case CGlobal::acModif:
			requete="UPDATE "+masterTable+" SET ";
			requete+="modification=CURDATE(), modificateur=\""+CMySQL::getInstance()->getUser()+"\", ";
			condition="WHERE "+primaryKey+"=\""+id->getValue()+"\"";
			break;
		default:
			return;
	}
	
	requete+="nom=\""+nom->getValue()+"\", adresse1=\""+adresse1->getValue()+"\", "; 
	requete+="adresse2=\""+adresse2->getValue()+"\", adresse3=\""+adresse3->getValue()+"\", "; 
	requete+="codePostal=\""+codePostal->getValue()+"\", ville=\""+ville->getValue()+"\", ";
	requete+="telephone=\""+telephone->getValue()+"\", ";
	requete+="fax=\""+fax->getValue()+"\", pays=\""+pays->getValue()+"\", ";
	requete+="mail=\""+mail->getValue()+"\", web=\""+web->getValue()+"\", ";
	requete+="siren=\""+siren->getValue()+"\", naf=\""+naf->getValue()+"\", ";
	requete+="tva=\""+tva->getValue()+"\", status=\""+status->getValue()+"\", ";
	requete+="formulePolitesse=\""+formulePolitesse->getValue()+"\", referencesBancaires=\""+referencesBancaires->getValue()+"\" ";
	if(pictureChange)
	{
		if(logo->picture() != NULL && !logo->picture()->isNull())
		{
			requete+=", logo=0x"+QString(pictureData.toHex())+" ";
		}else
		{
			requete+=", logo=NULL ";
		}
	}
	
	requete+=condition;
	
	if(CMySQL::getInstance()->execQuery(requete))
	{	
		setActionCur(CGlobal::acNone);
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::on_actAnnuler_triggered(void)
{
	
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir annuler ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes)
	{
		if(!chargeDonnees(curCode, CGlobal::seNone))
		{
			if(!chargeDonnees(curCode, CGlobal::sePrecedent))
			{
				if(!chargeDonnees(curCode, CGlobal::seSuivant))
				{
					setActionCur(CGlobal::acTableVide);
					return;
				}
			}
		}
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::on_actSupprimer_triggered(void)
{
	QMessageBox msgBox(	QMessageBox::Question, tr("Confirmation"), 
						tr("Etes vous sûre de vouloir supprimer la fiche courante ?"), QMessageBox::Yes | QMessageBox::No);
	msgBox.exec();
	
	if(msgBox.result() == QMessageBox::Yes)
	{
		if(!CMySQL::getInstance()->canDelete("client", "idSociete", curCode))
			return;
		if(!CMySQL::getInstance()->canDelete("prospect", "idSociete", curCode))
			return;
		
		QString requete="DELETE FROM "+masterTable+" WHERE "+primaryKey+"=\""+curCode+"\"";
		CMySQL::getInstance()->execQuery(requete);
		
		if(!chargeDonnees(curCode, CGlobal::sePrecedent))
		{
			if(!chargeDonnees(curCode, CGlobal::seSuivant))
			{
				setActionCur(CGlobal::acTableVide);
			}
		}
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::onChange(void)
{
	if(getActionCur() == CGlobal::acNone)
	{
		setActionCur(CGlobal::acModif);
	}
}
//------------------------------------------------------------------------------
void CSocieteFrm::on_actRechercheUneFiche_triggered(void)
{
	CFindFrm *findFrm=new CFindFrm(masterTable, this);
	
	findFrm->setModal(true);
	findFrm->exec();
	if(findFrm->result() == QDialog::Accepted)
	{
		chargeDonnees(findFrm->getResult(), CGlobal::seNone);
	}
	
	delete findFrm;
}
//------------------------------------------------------------------------------
void CSocieteFrm::onCombo(CMyComboBox *comboBox)
{
	CComboResultFrm *comboResultFrm=new CComboResultFrm(comboBox->getTableRemp(), comboBox->getChampRemp(), this);
	
	comboResultFrm->setModal(true);
	comboResultFrm->exec();
	
	if(comboResultFrm->result() == QDialog::Accepted)
	{
		comboBox->setValue(comboResultFrm->getResult());
	}
	
	delete comboResultFrm;
}
//------------------------------------------------------------------------------
void CSocieteFrm::onInvokeHelp(CChamp *champ)
{
	CHelp::getInstance()->startHelp("setSource qthelp://alpes-ressources.com.coMexpert-"+VERSION_LOGICIEL+"/doc/societe.html#"+champ->getTable()+"."+champ->getChamp());	
}
//------------------------------------------------------------------------------
void CSocieteFrm::on_logo_customContextMenuRequested(const QPoint& pos)
{
	actDropImage->setEnabled(logo->picture() != NULL && !logo->picture()->isNull());
	popupMenu->popup(logo->mapToGlobal(pos));
}
//------------------------------------------------------------------------------
void CSocieteFrm::actAddImage_triggered()
{
	setCursor(Qt::WaitCursor);
	QString fileName=QFileDialog::getOpenFileName(this, tr("Choisir un fichier"), QString(), tr("Images (*.png *.jpg)"));
	
	if(fileName != "")
	{
		QFileInfo fi(fileName);
		QString mimeType=CMimeType::getInstance()->getMimeType(fi.suffix());
		QFile file(fileName);
		
		fileName=fi.fileName();
		
		if(file.open(QIODevice::ReadOnly))
		{
			pictureChange=true;
			pictureData=file.readAll();
			loadImage(QImage::fromData(pictureData));
			file.close();
			if(getActionCur() == CGlobal::acNone)
			{
				setActionCur(CGlobal::acModif);
			}
		}
	}
	setCursor(Qt::ArrowCursor);
}
//------------------------------------------------------------------------------
void CSocieteFrm::actDropImage_triggered()
{
	loadImage(QImage());
	pictureChange=true;
	if(getActionCur() == CGlobal::acNone)
	{
		setActionCur(CGlobal::acModif);
	}
}
//------------------------------------------------------------------------------